/**
 * Author: w景洋.
 * Time: 2016/4/19 0019
 */
angular.module('usercenter.service.auth', [
        "ngResource",
        "ngStorage"
    ])
    //认证服务
    .service('AuthService', ['$resource', '$localStorage', '$location', '$http', '$q', '$stateParams','ShopMenuService',
        function ($resource, $localStorage, $location, $http, $q, $stateParams,ShopMenuService) {
            $storage = $localStorage.$default({
                userId: '',
                name: '',
                wxpay_openid: '',
                logo:'',
            });
            var self = this;
            var wxAuth = '';
            //会员信息提交
            this.save_userMembers = function (data, success_func, error_func) {
                data.userid = this.getUserid();
                var saveUserMember_url = $resource(uc_baseurl + 'usermember');
                return saveUserMember_url.save(data, success_func, error_func);
            }
            //根据userid获取会员信息
            this.get_userMembers = function () {
                var id = this.getUserid();
                var getUserMember_url = $resource(uc_baseurl + 'usermember/:uId');
                return getUserMember_url.get({uId: id});
            }
            //根据userid删除会员信息
            this.remove_userMembers = function () {
                var id = this.getUserid();
                var removeUserMember_url = $resource(uc_baseurl + 'usermember/:uId');
                return getUserMember_url.remove({uId: id});
            }
            // 获取验证码
            this.getcode = function (phone, success_func, error_func) {
                var GetPhoneCode = $resource(uc_baseurl + 'user/sendcode/:acount');
                var acount = "cf_linwenpin";
                GetPhoneCode.get({acount: acount, phone: phone}, success_func, error_func);
            }

            // 注册
            this.register = function (user, success_func, error_func) {
                var UserRegist = $resource(uc_baseurl + 'user');
                return UserRegist.save({code: user.code}, user, success_func, error_func);
            };

            // 登陆
            this.login = function (massage, success_func, error_func) {
                var UserLogin = $resource(uc_baseurl + 'user/login');
                return UserLogin.save(massage, success_func, error_func)
            };
            //通过用户名获取用户信息
            this.getUserByName  = function(name){
                var resource = $resource(uc_baseurl+"user/byname/:name");
                return resource.get({name:name});
            };
            //通过短信修改密码
            this.retrieve = function (user) {
                var Userretrieve = $resource(uc_baseurl + 'user/smsreset/password/:phone');
                return Userretrieve.save({phone: user.phone}, user);
            }

            //用户获取个人余额
            this.Userbalance = function () {
                var id = this.getUserid();
                var userbal = $resource(uc_baseurl + "userbalance/:userid");
                return userbal.get({userid: id});
            }
            //设置支付密码
            this.Userpaypassword = function (data, success, error) {
                var id = this.getUserid();
                var userbal = $resource(uc_baseurl + "balancepay/paysecret/:userid");
                return userbal.save({userid: id}, data, success, error);
            }
            //修改支付密码
            this.Resetpassword = function (data, success, error) {
                var id = this.getUserid();
                var usernewpassword = $resource(uc_baseurl + "userbalance/reset/paysecret/:userid");
                return usernewpassword.save({userid: id}, data, success, error);
            }
            //找回支付密码
            this.RetrievePaymentPassword = function (data, success, error) {
                var id = this.getUserid();
                var Retrievepassword = $resource(uc_baseurl + "userbalance/smsfind/password/:phone");
                data.userid = id;
                return Retrievepassword.get({phone: data.phone,code:data.code,paysecret:data.paysecret}, data, success, error);
            }
            //加入服务器购物车
            this.addToCartByUserId = function(goods,success,error){
                var addToCart = $resource(mallorder + "cart");
                return addToCart.save(goods,success,error)
            }
            //修改服务器购物车
            this.updateCartByCartId = function(goods,success,error){
                var updateCart = $resource(mallorder + "cart/:id");
                return updateCart.save({id:goods.cartid},goods,success,error);
            }
            // 注销
            this.logout = function () {
                $storage.userId = '';
                $storage.name = '';
                $storage.shopcart = {};
                $storage.order = '';
                $storage.orderid = '';
                $storage.wxpay_openid = '';
                $storage.logo = '';
            }

            // 已登录则返回userid，否则跳转指定地址
            this.ensure_login = function (jumpurl) {
                if ($storage.userId) {
                    return $storage.userId;
                }
                $location.path(jumpurl);
            }

            //获取用户id 为空则让他去登录
            this.getUserid = function () {
                if (!$storage.userId && $stateParams.way == 0) {
                    $location.path("/login/0");
                    return '';
                } else if (!$storage.userId) {
                    $location.path("/login/");
                    return '';
                }
                else {
                    return $storage.userId;
                }
            }

            //获取用户的name 为空让他去登录
            this.getUsername = function () {
                if (!$storage.name) {
                    $location.path("/login/");
                    return '';
                } else {
                    return $storage.name;
                }
            }
            //缓存数据赋值到新的对象避免操作时改变缓存
            this.storageShopCart = function(){
                var cartShop = []
                for (var shopid in $storage.shopcart) {
                    var shop={
                        shopid:shopid,
                        cartGoods:[]
                    }
                    shop.cartGoods.push()
                    cartShop.push(shop)
                }
            }
            //接口购物车数据和本地购物车数据同步
            this.shopCarMessage = function(){
                var hasProp = false;
                var shopCarMessage = $resource(mallorder + "cart/bybuyerid/:buyerid");
                var userId =this.getUserid();
                shopCarMessage.query({buyerid:userId}).$promise.then(function(data){
                    for (var shopid in $storage.shopcart) {
                        hasProp = true;
                        break;
                    }
                    if(hasProp == true){
                        for (var shopid in $storage.shopcart) {
                            for(var m=0;m<data.length;m++){
                                if(shopid == data[m].shopid){
                                    for(var i=0;i<$storage.shopcart[shopid].length;i++){
                                        for(var n=0;n<data[m].cartGoods.length;n++){

                                            if($storage.shopcart[shopid][i].goodsid==data[m].cartGoods[n].goodsid){
                                                data[m].cartGoods[n].num += $storage.shopcart[shopid][i].num;
                                                var good = data[m].cartGoods[n];
                                                var cartGood = {
                                                    cartid:good.cartid,
                                                    skuid: good.skuid,
                                                    num:good.num
                                                }
                                                self.updateCartByCartId(cartGood,function(){

                                                },function(){
                                                    alert("同步购物车失败");
                                                });
                                                $storage.shopcart[shopid].splice(i, 1);
                                            }
                                        }
                                    }
                                    for (var x = 0; x < $storage.shopcart[shopid].length; x++) {
                                        var goods = $storage.shopcart[shopid][x];
                                        var cartGoods = {
                                            buyerid: userId,
                                            shopid: goods.shopid,
                                            goodsid: goods.goodsid,
                                            skuid: goods.skuid,
                                            num: goods.num
                                        };
                                        self.addToCartByUserId(cartGoods,function(){
                                        },function(){
                                            alert("同步购物车失败");
                                        });
                                    }
                                    delete $storage.shopcart[shopid];
                                }
                            }
                        }
                        for (var shopid in $storage.shopcart) {
                            var shop = {
                                shopid:shopid,
                                cartGoods:[]
                            }
                            for(var j=0;j<$storage.shopcart[shopid].length;j++){
                                var goods = $storage.shopcart[shopid][j];
                                var cartGoods = {
                                    buyerid: userId,
                                    shopid: goods.shopid,
                                    goodsid: goods.goodsid,
                                    skuid: goods.skuid,
                                    num: goods.num
                                };
                                self.addToCartByUserId(cartGoods,function(){
                                },function(){
                                    alert("同步购物车失败");
                                });
                            }
                            $storage.shopcart[shopid] = '';
                        }
                    }
                },function(){
                    for (var shopid in $storage.shopcart) {
                        var shop = {
                            shopid:shopid,
                            cartGoods:[]
                        }
                        for(var j=0;j<$storage.shopcart[shopid].length;j++){
                            var goods = $storage.shopcart[shopid][j];
                            var cartGoods = {
                                buyerid: userId,
                                shopid: goods.shopid,
                                goodsid: goods.goodsid,
                                skuid: goods.skuid,
                                num: goods.num
                            };
                            self.addToCartByUserId(cartGoods,function(){
                            },function(){
                                alert("同步购物车失败");
                            });
                        }
                        delete  $storage.shopcart[shopid];
                    }
                });
            }
           /* //获取微信支付OpenID
            this.getOpenid = function () {
                var openid_res = $resource(uc_payconfig.wxpay_reaurl + "openid");
                    if (!$storage.wxpay_openid) {
                    var reg = new RegExp("(^|&)" + "code" + "=([^&]*)(&|$)");
                    var r = window.location.search.substr(1).match(reg);
                    var authcode = "xxxxxxxxxxxxxxxxxx";
                    if (r) {
                        authcode = unescape(r[2]);
                        var openid = openid_res.get({
                            wxspid: uc_payconfig.wxpay_spid,
                            code: authcode
                        }).$promise.then(function (data) {
                            if (data.openid) {
                                $storage.wxpay_openid = data.openid;
                            } else {
                                console.log("can't get openid by code=" + authcode);
                            }
                        }, function (error) {
                            console.log("code is invalid");
                        });
                        return openid;
                    } else {
                        console.log("can't find code");
                        return $storage.wxpay_openid;
                    }
                } else {
                    return $storage.wxpay_openid;
                }
            }*/
            //获取微信用户信息
            this.getstrogecode =function(){
                var wxuser =$resource(wxucURl + "wxauth/user");
                var reg = new RegExp("(^|&)" + "code" + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                var authcode = "xxxxxxxxxxxxxxxxxx";
                if (r) {
                    authcode = unescape(r[2]);
                    var userinfo_res = wxuser.get({
                        wxspid: uc_payconfig.wxpay_spid,
                        code: authcode
                    });
                    userinfo_res.$promise.then(function (data) {
                        wxAuth = data;
                    }, function (error) {
                    });
                    return userinfo_res;
                }else {
                    return "code is invalid";
                }
            };
            //微信登录确认
            this.getUserByWx = function(){
                return wxAuth;
            };
            //根据用户旧密码修改密码
            this.restPassword = function (data, success, error) {
                var restpassword = $resource(uc_baseurl + "user/reset/password/:phone")
                return restpassword.save({phone: data.phone}, data, success, error)
            };
            //获取用户信息
            this.getUserMessg = function () {
                var id = this.getUserid();
                var getuserMessg = $resource(uc_baseurl + "user/:id")
                return getuserMessg.get({id: id})
            }
            //修改用户名
            this.resetName = function (data, success, error) {
                var id = this.getUserid();
                var resetname = $resource(uc_baseurl + "user/:id")
                return resetname.save({id: id}, data, success, error)
            }
            //修改用户头像
            this.setUserhead = function (user, success, error) {
                var id = this.getUserid();
                var sethead = $resource(uc_baseurl + "user/:id")
                return sethead.save({id: id}, user, success, error);
            }
            //图片上传
            this.uploadFile = function (imgsrc, img, imgName) {
                var postData = {
                    filename: imgsrc,
                    file: img
                };
                var fd = new FormData();
                angular.forEach(postData, function (val, key) {
                    fd.append(key, val, imgName);
                });
                var deferred = $q.defer();
                $http({
                    method: 'POST',
                    url: uc_baseurl + 'fileupload/picupload',
                    data: fd,
                    headers: {'Content-Type': undefined},
                    transformRequest: angular.identity
                }).success(function (data, status, headers, config) {
                    deferred.resolve(data);
                }).error(function (data, status, headers, config) {
                    deferred.reject(data);
                });
                return deferred.promise;
            }
            //获取积分
            this.getUserpoints =function(id){
                var Userpoints = $resource(uc_baseurl +"userpoints/:id")
                var id = this.getUserid();
                return Userpoints.get({id:id})
            }
            this.exchangemony = function(exchange,success){
                var id = this.getUserid();
                var exchangemony = $resource(uc_baseurl +"userpoints/pointsconvert/balance/:userid")
                return exchangemony.save({userid:id,points:exchange},exchange,success)
            }
        }])

    //意见反馈*/
    .service('FeedbackService', ['$resource', 'AuthService', function ($resource, AuthService) {
        var feedbackInfo = $resource(uc_baseurl + 'feedback/');

        this.subFeedback = function (data) {
            var sugattr = {
                userid: AuthService.getUserid(),
                content: null
            }
            if (sugattr.userid != '') {
                sugattr.content = data;
                return feedbackInfo.save(sugattr);
            }
            else {
                alert("还未登录,请先登录!")
            }
        }

    }])